/*
 * nglist.cc
 */

#include "nglist.h"
#include "article.h"
#include "newsgroup.h"

/* Node constructor */
NgList::NgNode::NgNode(Newsgroup* v, NgNode* n) : ng(v), next(n) {}

/* Node destructor */
NgList::NgNode::~NgNode()
{
    delete ng;
    while(articles)
    {
        ANode* tmp = articles->next;
        delete articles;
        articles = tmp;
    }
}

/* Article node constructor */
NgList::ANode::ANode(Article* a, ANode* n) : a(a), next(n) {}

/* Article node destructor */
NgList::ANode::~ANode()
{
    delete a;
}

/* List constructor */
NgList::NgList() : head(NULL), tail(NULL), size(0) {}

/* List destructor */
NgList::~NgList() {
	//get rid of the nodes
    NgNode* n = head;
    while(n)
    {
        NgNode* tmp = n->next;
        delete n;
        n = tmp;
    }
    delete tail;
}

/* Add a node */
void NgList::addNg(Newsgroup* ng) {
	NgNode *n = new NgNode(ng, tail);
    if(head == NULL)
        head = n;
    else
        tail->next = n;
    tail = n;
}

void NgList::addArticle(Newsgroup* ng, Article a)
{
    NgNode* node = find(ng);
    ANode* an;
    *(an->a) = a;
    an->next = node->articles;
    node->articles = an;
}

NgList::NgNode* NgList::find(Newsgroup* ng) const
{
    NgNode* n = head;
    while(n)
    {
        if(*(n->ng) == *ng)
            return n;
        n = n->next;
    }
    return NULL;
}

/* Delete a node based on id */
void NgList::delNg(int id) {
    NgNode* n = head;
    while(n)
    {
        if(n->next->ng->getId() == id)
        {
            NgNode* d = n->next;
            n->next = d->next;
            delete d;
            return; // or should we remove all nodes with this id? (shouldnt be any more, right?)
        }
    }
}
